package com.ninong.ker.gateway.auth;

import java.security.Key;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import com.alibaba.fastjson.JSONObject;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;

/**
 * 安全管理文件
 * @author cmd
 *
 */
@Component
public class SecurityAdmin implements InitializingBean {

	@Autowired
	private JwtProperties properties;
	@Autowired
	private RedisTemplate<Object, Object> redisTemplate;
	private static final String AUTHORITIES_cmd = "auth";
	private Key key;

	@Override
	public void afterPropertiesSet() {
		byte[] cmdBytes = Decoders.BASE64.decode(properties.getSecret());
		this.key = Keys.hmacShaKeyFor(cmdBytes);
	}

	/**
	 * 获取当前登录用户
	 * 
	 * @param token
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<String> getAuthorities(String token) {
		Claims claims = Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).getBody();
		return (List<String>) claims.get(AUTHORITIES_cmd);
	}

	/**
	 * 校验token
	 * 
	 * @param authToken
	 * @return
	 */
	public boolean validateToken(String authToken) {
		Object token = redisTemplate.opsForValue().get(properties.getOnline() + authToken);
		if(!ObjectUtils.isEmpty(token)) {
			return true;			
		}
		return false;
	}

	/**
	 * 续时token
	 */
	public void checkRenewal(String token) {
		redisTemplate.expire(properties.getOnline() + token, properties.getValidity()/1000, TimeUnit.SECONDS);
	}

	/**
	 * 获取token
	 * 
	 * @param request
	 * @return
	 */
	public String getToken(ServerHttpRequest request) {
		final String requestHeader = request.getHeaders().getFirst(properties.getHeader());
		return requestHeader;
	}
	
	/**
	 * 是否开启接口校验
	 * @return
	 */
	public Boolean getAuth() {
		return properties.getSecurity();		
	}

	/**
	 * set token
	 * 
	 * @param response
	 * @param createToken
	 */
	public void setToken(ServerHttpResponse response, String createToken) {
		HttpHeaders headers = response.getHeaders();
		headers.add(properties.getHeader(), createToken);

	}
}
